<!--
 * @Description: 产品分析页面 - 提供产品数据的深度分析和可视化展示，支持查看全部跳转功能
 * @Author: lujq
 * @Date: 2024-12-21
 * @LastEditors: lujq
 * @LastEditTime: 2025-01-05 20:30:00
-->
<template>
  <div class="product-analytics">
    <!-- 产品概览 -->
    <div class="overview-section">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="6" v-for="item in overviewData" :key="item.title">
          <el-card class="overview-card" shadow="hover">
            <div class="card-content">
              <div class="card-icon" :style="{ backgroundColor: item.color }">
                <el-icon :size="20">
                  <component :is="item.icon" />
                </el-icon>
              </div>
              <div class="card-info">
                <div class="card-title">{{ item.title }}</div>
                <div class="card-value">{{ item.value }}</div>
                <div class="card-trend" :class="item.trend > 0 ? 'positive' : 'negative'">
                  <el-icon size="12">
                    <ArrowUp v-if="item.trend > 0" />
                    <ArrowDown v-else />
                  </el-icon>
                  {{ Math.abs(item.trend) }}%
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-section">
      <el-card>
        <el-form :model="filterForm" :inline="true" class="filter-form">
          <el-form-item label="产品类别">
            <el-select
              style="width: 160px"
              v-model="filterForm.category"
              placeholder="请选择产品类别"
              clearable
              @change="handleFilter"
              @clear="handleFilter"
            >
              <el-option label="真丝面料" value="silk" />
              <el-option label="棉质面料" value="cotton" />
              <el-option label="羊毛面料" value="wool" />
              <el-option label="化纤面料" value="synthetic" />
              <el-option label="混纺面料" value="blend" />
            </el-select>
          </el-form-item>
          <el-form-item label="价格区间">
            <el-select
              v-model="filterForm.priceRange"
              style="width: 160px"
              placeholder="请选择价格区间"
              clearable
              @change="handleFilter"
              @clear="handleFilter"
            >
              <el-option label="0-50元" value="0-50" />
              <el-option label="50-100元" value="50-100" />
              <el-option label="100-200元" value="100-200" />
              <el-option label="200元以上" value="200+" />
            </el-select>
          </el-form-item>
          <el-form-item label="库存状态">
            <el-select
              v-model="filterForm.stockStatus"
              style="width: 160px"
              placeholder="请选择库存状态"
              clearable
              @change="handleFilter"
              @clear="handleFilter"
            >
              <el-option label="充足" value="sufficient" />
              <el-option label="正常" value="normal" />
              <el-option label="不足" value="insufficient" />
              <el-option label="缺货" value="out_of_stock" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFilter">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
            <el-button type="success" @click="handleExport">
              <el-icon><Download /></el-icon>
              导出分析
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 图表分析区域 -->
    <div class="charts-section">
      <el-row :gutter="20">
        <!-- 产品销量排行 -->
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span class="card-title">产品销量排行</span>
                <el-select v-model="rankPeriod" size="small" style="width: 120px">
                  <el-option label="本周" value="week" />
                  <el-option label="本月" value="month" />
                  <el-option label="本季度" value="quarter" />
                  <el-option label="本年" value="year" />
                </el-select>
              </div>
            </template>
            <div ref="productRankChart" class="chart-container"></div>
          </el-card>
        </el-col>

        <!-- 产品类别分布 -->
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <span class="card-title">产品类别分布</span>
            </template>
            <div ref="categoryChart" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px">
        <!-- 产品生命周期 -->
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <span class="card-title">产品生命周期分析</span>
            </template>
            <div ref="lifecycleChart" class="chart-container"></div>
          </el-card>
        </el-col>

        <!-- 库存周转率 -->
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <span class="card-title">库存周转率</span>
            </template>
            <div ref="turnoverChart" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 产品价格分析 -->
      <el-row style="margin-top: 20px">
        <el-col :span="24">
          <el-card class="chart-card">
            <template #header>
              <span class="card-title">产品价格分析</span>
            </template>
            <div ref="priceChart" class="chart-container" style="height: 400px"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 产品利润分析 -->
      <el-row style="margin-top: 20px">
        <el-col :span="24">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span class="card-title">产品利润分析</span>
                <el-select v-model="profitMetric" size="small" style="width: 120px">
                  <el-option label="毛利率" value="gross" />
                  <el-option label="净利率" value="net" />
                  <el-option label="利润额" value="amount" />
                </el-select>
              </div>
            </template>
            <div ref="profitChart" class="chart-container" style="height: 400px"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 数据表格 -->
    <div class="data-section">
      <el-row :gutter="20">
        <!-- 热销产品 -->
        <el-col :xs="24" :lg="8">
          <el-card class="table-card">
            <template #header>
              <div class="card-header">
                <span class="card-title">热销产品TOP10</span>
                <el-button type="text" size="small" @click="viewAllHotProducts">
                  查看全部
                </el-button>
              </div>
            </template>
            <el-table :data="hotProducts" stripe max-height="300">
              <el-table-column prop="rank" label="排名" width="60" align="center" />
              <el-table-column prop="name" label="产品名称" show-overflow-tooltip />
              <el-table-column prop="sales" label="销量" width="80" align="right" />
            </el-table>
          </el-card>
        </el-col>

        <!-- 滞销产品 -->
        <el-col :xs="24" :lg="8">
          <el-card class="table-card">
            <template #header>
              <div class="card-header">
                <span class="card-title">滞销产品</span>
                <el-button type="text" size="small" @click="viewAllSlowProducts">
                  查看全部
                </el-button>
              </div>
            </template>
            <el-table :data="slowProducts" stripe max-height="300">
              <el-table-column prop="name" label="产品名称" show-overflow-tooltip />
              <el-table-column prop="stock" label="库存" width="80" align="right" />
              <el-table-column prop="days" label="滞销天数" width="100" align="right" />
            </el-table>
          </el-card>
        </el-col>

        <!-- 高利润产品 -->
        <el-col :xs="24" :lg="8">
          <el-card class="table-card">
            <template #header>
              <div class="card-header">
                <span class="card-title">高利润产品</span>
                <el-button type="text" size="small" @click="viewAllProfitProducts">
                  查看全部
                </el-button>
              </div>
            </template>
            <el-table :data="profitProducts" stripe max-height="300">
              <el-table-column prop="name" label="产品名称" show-overflow-tooltip />
              <el-table-column prop="profit" label="利润率" width="80" align="right">
                <template #default="{ row }"> {{ row.profit }}% </template>
              </el-table-column>
              <el-table-column prop="revenue" label="营收" width="100" align="right">
                <template #default="{ row }"> ¥{{ formatNumber(row.revenue) }} </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'
import {
  Box,
  Goods,
  TrendCharts,
  Money,
  ArrowUp,
  ArrowDown,
  Search,
  Refresh,
  Download,
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { formatNumber } from '@/utils'

// 路由实例
const router = useRouter()

// 图表实例
const productRankChart = ref<HTMLElement>()
const categoryChart = ref<HTMLElement>()
const lifecycleChart = ref<HTMLElement>()
const turnoverChart = ref<HTMLElement>()
const priceChart = ref<HTMLElement>()
const profitChart = ref<HTMLElement>()

let productRankChartInstance: echarts.ECharts
let categoryChartInstance: echarts.ECharts
let lifecycleChartInstance: echarts.ECharts
let turnoverChartInstance: echarts.ECharts
let priceChartInstance: echarts.ECharts
let profitChartInstance: echarts.ECharts

// 筛选表单
const filterForm = reactive({
  category: '',
  priceRange: '',
  stockStatus: '',
})

// 数据
const rankPeriod = ref('month')
const profitMetric = ref('gross')

// 概览数据
const overviewData = ref([
  {
    title: '产品总数',
    value: '1,234',
    trend: 8.5,
    icon: 'Box',
    color: '#409EFF',
  },
  {
    title: '在售产品',
    value: '892',
    trend: 12.3,
    icon: 'Goods',
    color: '#67C23A',
  },
  {
    title: '平均利润率',
    value: '28.5%',
    trend: -1.2,
    icon: 'TrendCharts',
    color: '#E6A23C',
  },
  {
    title: '产品总价值',
    value: '¥3.2M',
    trend: 15.7,
    icon: 'Money',
    color: '#F56C6C',
  },
])

// 热销产品数据
const hotProducts = ref([
  { rank: 1, name: '高档真丝面料', sales: 1256 },
  { rank: 2, name: '纯棉印花布', sales: 1134 },
  { rank: 3, name: '羊毛呢料', sales: 1028 },
  { rank: 4, name: '亚麻混纺布', sales: 956 },
  { rank: 5, name: '涤纶面料', sales: 887 },
  { rank: 6, name: '丝绸缎面', sales: 823 },
  { rank: 7, name: '棉麻混纺', sales: 756 },
  { rank: 8, name: '雪纺面料', sales: 689 },
  { rank: 9, name: '牛仔布料', sales: 634 },
  { rank: 10, name: '针织面料', sales: 578 },
])

// 滞销产品数据
const slowProducts = ref([
  { name: '特殊工艺面料A', stock: 234, days: 45 },
  { name: '限量版丝绸B', stock: 156, days: 38 },
  { name: '高端羊绒C', stock: 89, days: 32 },
  { name: '进口棉料D', stock: 67, days: 28 },
  { name: '定制面料E', stock: 45, days: 25 },
])

// 高利润产品数据
const profitProducts = ref([
  { name: '顶级真丝面料', profit: 45.6, revenue: 234000 },
  { name: '精品羊毛呢', profit: 38.9, revenue: 189000 },
  { name: '高档棉麻布', profit: 32.4, revenue: 156000 },
  { name: '特制混纺料', profit: 28.7, revenue: 134000 },
  { name: '进口亚麻布', profit: 25.3, revenue: 98000 },
])

// 基础产品数据
const baseProductData = {
  profit: [
    { name: '高档真丝面料', profit: 45.6, cost: 134.4, revenue: 234 },
    { name: '纯棉印花布', profit: 32.4, cost: 105.6, revenue: 156 },
    { name: '羊毛呢料', profit: 38.9, cost: 115.1, revenue: 189 },
    { name: '亚麻混纺布', profit: 28.7, cost: 95.3, revenue: 134 },
    { name: '涤纶面料', profit: 25.3, cost: 73.7, revenue: 98 },
  ],
  revenue: [
    { name: '高档真丝面料', revenue: 234, growth: 15.7 },
    { name: '纯棉印花布', revenue: 156, growth: 12.3 },
    { name: '羊毛呢料', revenue: 189, growth: 8.5 },
    { name: '亚麻混纺布', revenue: 134, growth: -1.2 },
    { name: '涤纶面料', revenue: 98, growth: 6.8 },
  ],
}

// 动态产品数据
let productProfitData = ref([...baseProductData.profit])
let productRevenueData = ref([...baseProductData.revenue])

/**
 * 生成产品销量排行数据
 */
const generateRankingData = () => {
  const baseData = {
    week: {
      names: ['高档真丝面料', '纯棉印花布', '羊毛呢料', '亚麻混纺布', '涤纶面料'],
      values: [156, 134, 128, 96, 87],
    },
    month: {
      names: ['高档真丝面料', '纯棉印花布', '羊毛呢料', '亚麻混纺布', '涤纶面料'],
      values: [1256, 1134, 1028, 956, 887],
    },
    quarter: {
      names: ['高档真丝面料', '纯棉印花布', '羊毛呢料', '亚麻混纺布', '涤纶面料'],
      values: [3768, 3402, 3084, 2868, 2661],
    },
    year: {
      names: ['高档真丝面料', '纯棉印花布', '羊毛呢料', '亚麻混纺布', '涤纶面料'],
      values: [15072, 13608, 12336, 11472, 10644],
    },
  }

  let data = baseData[rankPeriod.value as keyof typeof baseData] || baseData.month

  // 根据筛选条件调整数据
  if (filterForm.category || filterForm.priceRange || filterForm.stockStatus) {
    const factor = 0.8 + Math.random() * 0.4 // 0.8-1.2倍随机系数
    data = {
      names: [...data.names],
      values: data.values.map((val: number) => Math.round(val * factor)),
    }
  }

  return data
}

/**
 * 生成产品类别分布数据
 */
const generateCategoryData = () => {
  const baseData = [
    { value: 345, name: '真丝面料' },
    { value: 234, name: '棉质面料' },
    { value: 189, name: '羊毛面料' },
    { value: 156, name: '化纤面料' },
    { value: 98, name: '混纺面料' },
  ]

  // 根据筛选条件调整数据
  if (filterForm.category || filterForm.priceRange || filterForm.stockStatus) {
    const factor = 0.8 + Math.random() * 0.4
    return baseData.map((item) => ({
      ...item,
      value: Math.round(item.value * factor),
    }))
  }

  return baseData
}

/**
 * 生成库存周转率数据
 */
const generateTurnoverData = () => {
  const baseData = {
    categories: ['真丝面料', '棉质面料', '羊毛面料', '化纤面料', '混纺面料'],
    values: [8.5, 6.8, 5.2, 9.1, 7.3],
  }

  // 根据筛选条件调整数据
  if (filterForm.category || filterForm.priceRange || filterForm.stockStatus) {
    const factor = 0.8 + Math.random() * 0.4
    return {
      categories: baseData.categories,
      values: baseData.values.map((val) => Math.round(val * factor * 10) / 10),
    }
  }

  return baseData
}

/**
 * 生成利润分析数据
 */
const generateProfitData = () => {
  const baseData = {
    categories: ['真丝面料', '棉质面料', '羊毛面料', '化纤面料', '混纺面料'],
    gross: [45.6, 32.4, 38.9, 28.7, 35.2],
    net: [35.2, 25.8, 29.6, 22.3, 27.1],
    amount: [234, 156, 189, 134, 167],
  }

  // 根据利润指标和筛选条件调整数据
  let factor = 1
  if (filterForm.category || filterForm.priceRange || filterForm.stockStatus) {
    factor = 0.8 + Math.random() * 0.4
  }

  return {
    categories: baseData.categories,
    gross: baseData.gross.map((val) => Math.round(val * factor * 10) / 10),
    net: baseData.net.map((val) => Math.round(val * factor * 10) / 10),
    amount: baseData.amount.map((val) => Math.round(val * factor)),
  }
}

/**
 * 根据筛选条件更新数据
 */
const updateDataByFilter = () => {
  // 更新产品利润和收入数据
  const factor = 0.8 + Math.random() * 0.4

  productProfitData.value = baseProductData.profit.map((item) => ({
    ...item,
    profit: Math.round(item.profit * factor * 10) / 10,
    cost: Math.round(item.cost * factor * 10) / 10,
    revenue: Math.round(item.revenue * factor),
  }))

  productRevenueData.value = baseProductData.revenue.map((item) => ({
    ...item,
    revenue: Math.round(item.revenue * factor),
    growth: Math.round((item.growth + (Math.random() - 0.5) * 10) * 10) / 10,
  }))
}

/**
 * 更新所有图表
 */
const updateCharts = () => {
  if (productRankChartInstance) {
    const rankingData = generateRankingData()
    productRankChartInstance.setOption({
      yAxis: { data: rankingData.names },
      series: [{ data: rankingData.values }],
    })
  }

  if (categoryChartInstance) {
    const categoryData = generateCategoryData()
    categoryChartInstance.setOption({
      series: [{ data: categoryData }],
    })
  }

  if (turnoverChartInstance) {
    const turnoverData = generateTurnoverData()
    turnoverChartInstance.setOption({
      xAxis: { data: turnoverData.categories },
      series: [{ data: turnoverData.values }],
    })
  }

  if (profitChartInstance) {
    const profitData = generateProfitData()
    profitChartInstance.setOption({
      xAxis: { data: profitData.categories },
      series: [{ data: profitData.gross }, { data: profitData.net }, { data: profitData.amount }],
    })
  }
}

/**
 * 重置为初始数据
 */
const resetToInitialData = () => {
  productProfitData.value = [...baseProductData.profit]
  productRevenueData.value = [...baseProductData.revenue]
}

/**
 * 筛选处理
 */
const handleFilter = () => {
  ElMessage.success('筛选成功')
  console.log('筛选条件:', filterForm)
  updateDataByFilter()
  updateCharts()
}

/**
 * 重置筛选条件
 */
const handleReset = () => {
  filterForm.category = ''
  filterForm.priceRange = ''
  filterForm.stockStatus = ''
  resetToInitialData()
  updateCharts()
  ElMessage.info('筛选条件已重置')
}

/**
 * 导出分析
 */
const handleExport = () => {
  ElMessage.success('产品分析报告导出中...')
}

/**
 * 查看全部热销产品
 * @description 跳转到产品列表页，并按销量降序展示
 */
const viewAllHotProducts = () => {
  router.push({
    name: 'ProductList',
    query: {
      sortBy: 'sales',
      sortOrder: 'desc',
      title: '热销产品列表'
    }
  })
}

/**
 * 查看全部滞销产品
 * @description 跳转到产品列表页，并按销量升序展示
 */
const viewAllSlowProducts = () => {
  router.push({
    name: 'ProductList',
    query: {
      sortBy: 'sales',
      sortOrder: 'asc',
      title: '滞销产品列表'
    }
  })
}

/**
 * 查看全部高利润产品
 * @description 跳转到产品列表页，以价格作为利润替代字段按降序展示
 */
const viewAllProfitProducts = () => {
  router.push({
    name: 'ProductList',
    query: {
      sortBy: 'price',
      sortOrder: 'desc',
      title: '高利润产品列表'
    }
  })
}

/**
 * 初始化产品排行图表
 */
const initProductRankChart = () => {
  if (!productRankChart.value) return

  productRankChartInstance = echarts.init(productRankChart.value)

  // 根据筛选条件和时间周期生成数据
  const rankingData = generateRankingData()

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'value',
    },
    yAxis: {
      type: 'category',
      data: rankingData.names,
    },
    series: [
      {
        name: '销量',
        type: 'bar',
        data: rankingData.values,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' },
          ]),
        },
      },
    ],
  }

  productRankChartInstance.setOption(option)
}

/**
 * 初始化产品类别图表
 */
const initCategoryChart = () => {
  if (!categoryChart.value) return

  categoryChartInstance = echarts.init(categoryChart.value)

  // 根据筛选条件生成数据
  const categoryData = generateCategoryData()

  const option = {
    tooltip: {
      trigger: 'item',
    },
    legend: {
      orient: 'vertical',
      left: 'left',
    },
    series: [
      {
        name: '产品类别',
        type: 'pie',
        radius: '50%',
        data: categoryData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  }

  categoryChartInstance.setOption(option)
}

/**
 * 初始化产品生命周期图表
 */
const initLifecycleChart = () => {
  if (!lifecycleChart.value) return

  lifecycleChartInstance = echarts.init(lifecycleChart.value)

  const option = {
    tooltip: {
      trigger: 'item',
    },
    series: [
      {
        name: '产品生命周期',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2,
        },
        label: {
          show: false,
          position: 'center',
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 20,
            fontWeight: 'bold',
          },
        },
        labelLine: {
          show: false,
        },
        data: [
          { value: 156, name: '导入期' },
          { value: 234, name: '成长期' },
          { value: 345, name: '成熟期' },
          { value: 89, name: '衰退期' },
        ],
      },
    ],
  }

  lifecycleChartInstance.setOption(option)
}

/**
 * 初始化库存周转率图表
 */
const initTurnoverChart = () => {
  if (!turnoverChart.value) return

  turnoverChartInstance = echarts.init(turnoverChart.value)

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: ['真丝面料', '棉质面料', '羊毛面料', '化纤面料', '混纺面料'],
    },
    yAxis: {
      type: 'value',
      name: '周转率(次/年)',
    },
    series: [
      {
        name: '周转率',
        type: 'bar',
        data: [8.5, 6.8, 5.2, 9.1, 7.3],
        itemStyle: {
          color: '#67C23A',
        },
      },
    ],
  }

  turnoverChartInstance.setOption(option)
}

/**
 * 初始化产品价格图表
 */
const initPriceChart = () => {
  if (!priceChart.value) return

  priceChartInstance = echarts.init(priceChart.value)

  const option = {
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      data: ['平均价格', '最高价格', '最低价格'],
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
    },
    yAxis: {
      type: 'value',
      name: '价格(元/米)',
    },
    series: [
      {
        name: '平均价格',
        type: 'line',
        data: [85, 88, 92, 89, 95, 98, 102, 105, 108, 112, 115, 118],
        smooth: true,
        itemStyle: {
          color: '#409EFF',
        },
      },
      {
        name: '最高价格',
        type: 'line',
        data: [125, 128, 132, 129, 135, 138, 142, 145, 148, 152, 155, 158],
        smooth: true,
        itemStyle: {
          color: '#F56C6C',
        },
      },
      {
        name: '最低价格',
        type: 'line',
        data: [45, 48, 52, 49, 55, 58, 62, 65, 68, 72, 75, 78],
        smooth: true,
        itemStyle: {
          color: '#67C23A',
        },
      },
    ],
  }

  priceChartInstance.setOption(option)
}

/**
 * 初始化产品利润图表
 */
const initProfitChart = () => {
  if (!profitChart.value) return

  profitChartInstance = echarts.init(profitChart.value)

  const option = {
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      data: ['毛利率', '净利率', '利润额'],
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: ['真丝面料', '棉质面料', '羊毛面料', '化纤面料', '混纺面料'],
    },
    yAxis: [
      {
        type: 'value',
        name: '利润率(%)',
        position: 'left',
      },
      {
        type: 'value',
        name: '利润额(万元)',
        position: 'right',
      },
    ],
    series: [
      {
        name: '毛利率',
        type: 'bar',
        yAxisIndex: 0,
        data: [45.6, 32.4, 38.9, 28.7, 35.2],
        itemStyle: {
          color: '#409EFF',
        },
      },
      {
        name: '净利率',
        type: 'bar',
        yAxisIndex: 0,
        data: [35.2, 25.8, 29.6, 22.3, 27.1],
        itemStyle: {
          color: '#67C23A',
        },
      },
      {
        name: '利润额',
        type: 'line',
        yAxisIndex: 1,
        data: [234, 156, 189, 134, 167],
        smooth: true,
        itemStyle: {
          color: '#E6A23C',
        },
      },
    ],
  }

  profitChartInstance.setOption(option)
}

// 监听排行周期变化
watch(rankPeriod, () => {
  console.log('更新产品排行:', rankPeriod.value)
  updateCharts()
})

// 监听利润指标变化
watch(profitMetric, () => {
  console.log('更新利润指标:', profitMetric.value)
  updateCharts()
})

/**
 * 窗口大小变化时重新调整图表
 */
const handleResize = () => {
  productRankChartInstance?.resize()
  categoryChartInstance?.resize()
  lifecycleChartInstance?.resize()
  turnoverChartInstance?.resize()
  priceChartInstance?.resize()
  profitChartInstance?.resize()
}

onMounted(async () => {
  await nextTick()

  // 初始化所有图表
  initProductRankChart()
  initCategoryChart()
  initLifecycleChart()
  initTurnoverChart()
  initPriceChart()
  initProfitChart()

  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})
</script>

<style scoped>
.product-analytics {
  padding: 0;
}

.overview-section {
  margin-bottom: 20px;
}

.overview-card {
  height: 100px;
  cursor: pointer;
  transition: all 0.3s;
}

.overview-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.card-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.card-icon {
  width: 50px;
  height: 50px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  color: white;
}

.card-info {
  flex: 1;
}

.card-title {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.card-value {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 2px;
}

.card-trend {
  font-size: 11px;
  display: flex;
  align-items: center;
  gap: 2px;
}

.card-trend.positive {
  color: #67c23a;
}

.card-trend.negative {
  color: #f56c6c;
}

.filter-section {
  margin-bottom: 20px;
}

.filter-form {
  margin: 0;
}

.charts-section {
  margin-bottom: 20px;
}

.chart-card,
.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.chart-container {
  height: 300px;
  width: 100%;
}

.data-section {
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .overview-card {
    margin-bottom: 16px;
  }

  .card-content {
    flex-direction: column;
    text-align: center;
  }

  .card-icon {
    margin-right: 0;
    margin-bottom: 8px;
  }

  .chart-container {
    height: 250px;
  }

  .card-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }

  .filter-form {
    display: block;
  }

  .filter-form .el-form-item {
    display: block;
    margin-bottom: 16px;
  }
}
</style>
